package com.zzyl.framework.security.filter;

import java.io.IOException;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import com.zzyl.common.core.domain.model.LoginUser;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.framework.web.service.TokenService;

/**
 * JWT 过滤器：验证 Token 有效性并建立安全上下文
 *
 * @author liuyp (updated by Qwen)
 */
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Autowired
    private TokenService tokenService;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
            throws ServletException, IOException {

        try {
            // 从请求中获取 LoginUser（通过 Token 解析）
            LoginUser loginUser = tokenService.getLoginUser(request);

            // 如果 loginUser 不为空，并且当前 SecurityContext 中还没有认证信息
            if (loginUser != null && SecurityContextHolder.getContext().getAuthentication() == null) {

                // 验证 Token 是否有效（检查是否过期等）
                tokenService.verifyToken(loginUser);

                // 创建 Spring Security 的 Authentication 对象
                UsernamePasswordAuthenticationToken authenticationToken =
                        new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());

                // 设置请求详情（如 remote address, session id）
                authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));

                // 将认证信息设置到 SecurityContext 中
                SecurityContextHolder.getContext().setAuthentication(authenticationToken);
            }
        } catch (Exception e) {
            // 捕获认证过程中的异常，避免中断过滤器链
            // 可根据需要记录日志
        }

        // 继续执行过滤器链
        chain.doFilter(request, response);
    }
}